import React, { useRef, useState } from 'react';
import { Button, Card, DatePicker, Form, message, Spin } from 'antd';
import moment from 'moment';
import bigDecimal from 'js-big-decimal';
import { useMount } from 'react-use';

import { isSuccess } from '@/utils/request';
import pageTabUtil from '@/utils/pageTabUtil';
import { withRoutePage } from '@/utils/enhanceUtils';
import { BottomAction } from '@/components';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import { getSpecialTaxById, updateSpecialTax } from '@/services/salaryManage/salaryCalculate';
import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';
import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';

const { Item } = Form;
const { MonthPicker } = DatePicker;

const numberOption = name => ({
    validateFirst: true,
    rules: [
        {
            required: true,
            message: `请填写【${name}】金额`
        },
        {
            type: 'number',
            min: 0,
            message: `【${name}】不能小于0`
        },
        {
            type: 'number',
            max: 9999999999.99,
            message: `【${name}】不能超过10亿`
        },
        {
            type: 'number',
            message: `【${name}】输入长度不能大于12`
        },
        {
            validator: (rule, value, callback) => {
                const dotPosition = String(value).indexOf('.');
                // 小数位数超过8位时
                if (
                    dotPosition > 0 &&
                    String(value).length > dotPosition + 1 &&
                    String(value).substr(dotPosition + 1).length > 8
                ) {
                    callback(new Error());
                } else {
                    callback();
                }
            },
            message: '小数位数不能超过8位'
        }
    ]
});

const wrapperPageModel = pageModel => {
    const { yearMonth, ...rel } = pageModel;
    // 所属月份
    if (yearMonth) {
        rel.v_period = moment(`${yearMonth}`);
    }

    return { ...rel, yearMonth };
};

const getPostData = (pageModel, formValue) => {
    const { v_period, ...otherFormValue } = formValue;
    return { ...pageModel, ...otherFormValue };
};

const FieldSpecial = ({ form, pageModel, wrapperFormRef }) => {
    wrapperFormRef(form);
    const { getFieldDecorator } = form;

    const [loading, setLoading] = useState(false);

    // 取消
    const onCancel = () => pageTabUtil.closeTab();

    // 保存
    const onSave = () => {
        form.validateFieldsAndScroll((errors, values) => {
            if (errors) {
                return;
            }

            const postData = getPostData(pageModel, values);
            setLoading(true);
            updateSpecialTax(postData)
                .then(response => {
                    setLoading(false);
                    if (!isSuccess(response)) {
                        message.error(response.msg);
                        return;
                    }
                    message.success('保存成功！');
                    tabMessageUtil.noticeFromRefresh();
                    pageTabUtil.closeTab();
                })
                .catch(() => {
                    setLoading(false);
                });
        });
    };

    return (
        <Form layout="horizontal" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} style={{ maxWidth: '430px' }}>
            <Item label="行政机构">
                <OrganizationNameConnect organizationCode={ pageModel?.organizationCode} />
            </Item>
            <Item label="员工姓名">
                <span style={{ whiteSpace: 'nowrap' }}>
                    {pageModel?.employeeNo} {pageModel?.name}
                </span>
            </Item>
            <Item label="所属月份">
                {getFieldDecorator('v_period', {
                    initialValue: pageModel?.v_period
                })(<MonthPicker disabled />)}
            </Item>
            <Item label="累计-子女教育">
                {getFieldDecorator('childEducationAmt', {
                    initialValue: pageModel?.childEducationAmt,
                    ...numberOption('子女教育')
                })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
            </Item>
            <Item label="累计-继续教育">
                {getFieldDecorator('continueEducationAmt', {
                    initialValue: pageModel?.continueEducationAmt,
                    ...numberOption('继续教育')
                })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
            </Item>
            <Item label="累计-住房贷款利息">
                {getFieldDecorator('houseLoanInterestAmt', {
                    initialValue: pageModel?.houseLoanInterestAmt,
                    ...numberOption('住房贷款利息')
                })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
            </Item>
            <Item label="累计-住房租金">
                {getFieldDecorator('houseLeaseAmt', {
                    initialValue: pageModel?.houseLeaseAmt,
                    ...numberOption('住房租金')
                })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
            </Item>
            <Item label="累计-赡养老人">
                {getFieldDecorator('raiseOldAmt', {
                    initialValue: pageModel?.raiseOldAmt,
                    ...numberOption('赡养老人')
                })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
            </Item>
            <Item label="累计-合计">
                {getFieldDecorator('totalSpecialAmt', {
                    initialValue: pageModel?.totalSpecialAmt
                })(<NumberSettingInput thousandsSeparator="," maxLength={15} disabled />)}
            </Item>
            <BottomAction>
                <Button onClick={onCancel}>取消</Button>
                <Button type="primary" disabled={loading} onClick={onSave}>
                    确定
                </Button>
            </BottomAction>
        </Form>
    );
};

const SalaryPayrollTaxEdit = ({ location }) => {
    const [loading, setLoading] = useState(false);
    const [pageModel, setPageModel] = useState({});
    const formRef = useRef(null);

    const { id } = location.query;

    const reduceFn = arr => arr.reduce((total, item) => bigDecimal.add(total, item || 0), 0);

    // 合计计算
    const changeVal = data => {
        const {
            childEducationAmt,
            continueEducationAmt,
            houseLoanInterestAmt,
            houseLeaseAmt,
            raiseOldAmt,
            totalSpecialAmt
        } = data;
        const totals = reduceFn([
            childEducationAmt,
            continueEducationAmt,
            houseLoanInterestAmt,
            houseLeaseAmt,
            raiseOldAmt
        ]);
        if (totals !== totalSpecialAmt) {
            // 需要等页面渲染完成才计算，否则会前后错乱导致合计算错
            setTimeout(() => {
                formRef.current.setFieldsValue({
                    totalSpecialAmt: totals
                });
            }, 0);
        }
    };

    useMount(async () => {
        setLoading(true);
        try {
            const [pageModelResponse] = await Promise.all([getSpecialTaxById({ id })]);
            setLoading(false);

            if (isSuccess(pageModelResponse)) {
                setPageModel(wrapperPageModel(pageModelResponse.data));
            } else {
                message.error(pageModelResponse.msg);
            }
        } catch (e) {
            setLoading(false);
        }
    });

    const FieldSpecialWrapper = Form.create({
        onValuesChange(_, values, allValues) {
            changeVal(allValues);
        }
    })(FieldSpecial);

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={pageModel.organizationCode}>
                <Card bordered={false} title="编辑专项扣款">
                    <Spin spinning={loading}>
                        <FieldSpecialWrapper
                            pageModel={pageModel}
                            wrapperFormRef={form => {
                                formRef.current = form;
                            }}
                        />
                    </Spin>
                </Card>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(SalaryPayrollTaxEdit);
